﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RapidWebDev.UI.DynamicPages;
using RapidWebDev.Platform;
using RapidWebDev.Common;
using TestCenter.Platform.Apis;
using TestCenter.Platform.DataModel;
using RapidWebDev.Common.Data;
using System.Linq.Expressions;
using RapidWebDev.ExtensionModel;

using System.Collections.ObjectModel;
using System.Configuration;
using System.Data.Common;
using System.Web;
using System.Web.Profile;
using System.Web.Security;

using RapidWebDev.Common.Caching;

using RapidWebDev.Common.Globalization;
using RapidWebDev.Common.Validation;

using RapidWebDev.Platform.Initialization;
using RapidWebDev.Platform.Properties;

namespace TestCenter.Platform.Web.DynamicPages
{
    public class TestProjectManagement : DynamicPage
    {
        protected static readonly IAuthenticationContext authenticationContext = SpringContext.Current.GetObject<IAuthenticationContext>();

        protected static readonly ITestCenterApi testCenterApi = SpringContext.Current.GetObject<ITestCenterApi>();

        protected static readonly IHierarchyApi hierarchyApi = SpringContext.Current.GetObject<IHierarchyApi>();

        public override QueryResults Query(QueryParameter parameter)
        {
            LinqPredicate predicate = parameter.Expressions.Compile();
            //Get HierarchyData By parentId
            string parentId;
            if (!string.IsNullOrEmpty(authenticationContext.Session["CurrentProject"].ToString()))
                parentId = authenticationContext.Session["CurrentProject"].ToString();

            var q = hierarchyApi.GetAllHierarchyData("0");

            IList<string> queryCode = new List<string>();
            foreach(var tmp in q)
            {
                queryCode.Add(tmp.Code);
            }

            using (TestCenterDataContext ctx = DataContextFactory.Create<TestCenterDataContext>())
            {
                int recordCount;
                string sortExpression = null;
                if (parameter.SortExpression != null)
                    sortExpression = parameter.SortExpression.Compile();

                if (Kit.IsEmpty(sortExpression))
                    sortExpression = "CreateDate DESC";

                var result = from tp in ctx.TestProjects
                             where queryCode.ToArray().Contains(tp.Id.ToString())
                             select tp;

                if (predicate != null && !Kit.IsEmpty(predicate.Expression))
                    result = result.Where(predicate.Expression, predicate.Parameters);
                recordCount = result.Count();

                List<TestProject> ret = result.Skip(parameter.PageIndex * parameter.PageSize).Take(parameter.PageSize).ToList();

                return new QueryResults(recordCount, ret);
            }
        }


    }
}
